﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.DAL;
using ZBJF.Warranty.IDAL;
using ZBJF.Warranty.IDAL.IRepositories;
using ZBJF.Warranty.Model.ViewModel.BaseQueryModel;

namespace ZBJF.Warranty.BLL
{
    public abstract class BaseService<T> where T : class, new()
    {
        //在调用这个属性的时候必须给它赋值
        public IBaseRepository<T> CurrentRepository { get; set; }


        public IDbSession DbSession = DbSessionFactory.GetCurrentDbSession();

        public BaseService()
        {
            SetCurrentRepository(); //构造函数里面调用了此设置当前仓储的抽象方法
        }

        //构造方法实现赋值 
        public abstract void SetCurrentRepository(); //约束子类必须实现这个抽象方法

        public T AddEntities(T entity)
        {
            //如果在这里操作多个表的话，实现批量的操作
            //调用T对应的仓储来添加
            var addentity = CurrentRepository.AddEntities(entity);

            DbSession.SaveChanges();
            return addentity;
        }

        public bool UpdateEntities(T entity)
        {
            CurrentRepository.UpdateEntities(entity);
            return DbSession.SaveChanges() > 0;
        }
        public bool DeleteEntities(T entity)
        {
            CurrentRepository.DeleteEntities(entity);
            return DbSession.SaveChanges() > 0;
        }

        public IQueryable<T> LoadEntities(Expression<Func<T, bool>> wherelambda)
        {
            return CurrentRepository.LoadEntities(wherelambda);
        }

        public IQueryable<T> LoadPagerEntities<S>(int pageIndex, int pageSize,
            out int total, Expression<Func<T, bool>> whereLambda, string orderByExpression)// Expression<Func<T, S>> 
        {
            return CurrentRepository.LoadPagerEntities<S>(pageIndex, pageSize, out total, whereLambda, OrderString2ModelFieldArr.ConvertToModelField(orderByExpression));
        }
        public int ExcuteSql(string strSql, SqlParameter[] parameters)
        {
            return CurrentRepository.ExcuteSql(strSql, parameters);
        }
        public object ExecuteScalar(string strSql, SqlParameter[] parameters)
        {
            return CurrentRepository.ExecuteScalar(strSql, parameters);
        }
        public DataTable SqlQuery(string strSql, params SqlParameter[] parameters)
        {
            return CurrentRepository.SqlQuery(strSql, parameters);
        }

    }
}
